package com.tsh.erp.controllers;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kiven.jee.utils.common.Constants;
import kiven.jee.utils.encrypter.IPasswordEncrypter;
import kiven.jee.utils.encrypter.md5.PasswordMd5Encrypter;
import kiven.jee.utils.web.CookieUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tsh.erp.model.User;
import com.tsh.erp.service.UserService;
import com.tsh.erp.support.AppHelper;
import com.tsh.erp.support.OnlineUserHelper;

@Controller
@RequestMapping("/user")
public class LoginController {
	@Resource(name = "userService")
	private UserService userService;

	private IPasswordEncrypter encrypter = new PasswordMd5Encrypter();

	private Logger logger = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> login(User user, String code,
			HttpServletRequest request, HttpServletResponse response) {
		// 验证码
		String kaptchaExpected = (String) request.getSession().getAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

		// 操作结果
		Map<String, Object> result = new HashMap<String, Object>();

		// 记住我选项
		String rememberme = request.getParameter("rememberme");

		if (!kaptchaExpected.equals(code)) {// 判断验证码是否正确
			result.put("msg", "验证码输入错误!");
		} else {

			User user2 = userService.login(user.getUserid(),
					encrypter.encryptPassword(user.getPassword()), request);
			if (user2 != null) {
				if (user2.getAccountlocked() == 1
						|| "0".equals(user2.getEnabled())) {
					result.put("msg", "该用户未激活或已处于锁定状态!");
				} else if (user2.getPassworderrcnt() >= 5) {
					result.put("msg", "登录失败超过5次，用户锁定!");
				} else {// 登录成功
					if (OnlineUserHelper.existUser(user2.getUserid())) {
						OnlineUserHelper.removeOnlineUserByUserid(user2
								.getUserid());

						// 第二次登录
					}

					// 处理Cookie
					if (Constants.REMEMBERME_VAULE.equals(rememberme)) {
						try {
							CookieUtil.setCookie(response,
									Constants.COOKIE_USERNAME,
									user2.getUsername(),
									request.getContextPath());
							CookieUtil.setCookie(response,
									Constants.COOKIE_PASSWORD, encrypter
											.encryptPassword(user2
													.getPassword()), request
											.getContextPath());

						} catch (Exception e) {
							logger.error("cookie设置出错", e.getCause());
						}
					}

					// 登入成功后将用户显示为在线用户
					OnlineUserHelper.addOnlineUser(
							request.getSession().getId(), user2);

					// 将User放入Session中
					AppHelper.setAuthUser(request, user2);

					result.put("sessionid", request.getSession().getId());
					result.put("success", true);
				}
			} else {
				User user3 = userService.findUserByPropertyName("userid",
						user.getUserid());
				if (user3 != null) {
					if (user3.getAccountlocked() == 1
							|| "0".equals(user3.getEnabled())) {
						result.put("msg", "该用户未激活或已处于锁定状态!");
					} else if (user3.getPassworderrcnt() >= 5) {
						result.put("msg", "登录失败超过5次，用户锁定!");
					} else {
						result.put("msg", "密码输入错误!");
					}
				} else {
					result.put("msg", "用户不存在!");
				}
			}
		}
		return result;
	}

	/*
	 * @RequestMapping("/exchange") public String
	 * exchange(@RequestParam("sessionid") String sessionid) { String url =
	 * "login"; OnlineUser onlineUser = OnlineUserHelper
	 * .getOnlineUserBySessionid(sessionid);
	 * 
	 * if (onlineUser != null) { url = "index"; }
	 * 
	 * return "redirect:/"; }
	 */

	@RequestMapping("/exchangex")
	public String exchangex(HttpServletRequest request) {
		String url = "redirect:/";

		User u = AppHelper.getAuthUser(request);

		if (u != null) {
			url = "index";
		}

		return url;
	}
}
